<template>
  <div class="discussion-detail-page">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-container">
        <div class="navbar-left">
          <router-link to="/" class="logo-link">
            <svg class="logo-icon" viewBox="0 0 48 48" width="36" height="36" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect width="48" height="48" rx="12" fill="url(#logoGradient)"/>
              <path d="M12 32V16L18 24L24 16L30 24L36 16V32" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
              <circle cx="18" cy="25" r="1.5" fill="white" opacity="0.8"/>
              <circle cx="30" cy="25" r="1.5" fill="white" opacity="0.8"/>
              <defs>
                <linearGradient id="logoGradient" x1="0" y1="0" x2="48" y2="48" gradientUnits="userSpaceOnUse">
                  <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
                  <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
                </linearGradient>
              </defs>
            </svg>
            <span class="logo">M-Learning</span>
          </router-link>
        </div>
        
        <div class="navbar-center">
          <router-link to="/home" class="nav-link">首页</router-link>
          <router-link to="/discussion" class="nav-link">帖子</router-link>
        </div>
        
        <div class="navbar-right">
          <div class="user-dropdown" @mouseenter="showUserMenu = true" @mouseleave="showUserMenu = false">
            <div class="user-info-trigger">
              <div class="user-avatar" @click="handleAvatarClick" style="cursor: pointer;" title="点击更换头像">
                <img 
                  v-if="userInfo && userInfo.avatar" 
                  :src="getAvatarUrl(userInfo.avatar)" 
                  alt="头像"
                />
                <span v-else class="avatar-placeholder">
                  {{ userInfo?.nickname?.charAt(0) || userInfo?.phone?.charAt(userInfo.phone.length - 1) || '未' }}
                </span>
              </div>
              <span class="user-display-name">{{ userInfo?.nickname || userInfo?.phone || '未登录' }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <div class="content-container">
        <!-- 返回按钮 -->
        <button class="back-btn" @click="goBack">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
            <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
          </svg>
          返回帖子列表
        </button>

        <!-- 讨论内容 -->
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="discussion" class="discussion-content">
          <!-- 标题和作者信息 -->
          <div class="discussion-header">
            <h1 class="discussion-title">{{ discussion.title }}</h1>
            <div class="author-info">
              <div 
                class="author-avatar"
                @mouseenter="handleUserHover(discussion.author.id, $event)"
                @mouseleave="handleUserLeave"
              >
                <img 
                  v-if="discussion.author.avatar" 
                  :src="getAvatarUrl(discussion.author.avatar)" 
                  :alt="discussion.author.nickname"
                />
                <span v-else class="avatar-text">
                  {{ discussion.author.nickname?.charAt(0) || 'U' }}
                </span>
              </div>
              <div class="author-details">
                <div class="author-name">{{ discussion.author.nickname }}</div>
                <div class="publish-info">
                  来自 {{ discussion.author.location || userInfo?.location || '中国' }} · {{ formatTime(discussion.createdAt) }}
                </div>
              </div>
            </div>
            <div class="discussion-tags">
              <span v-for="tag in discussion.tags" :key="tag" class="tag">{{ tag }}</span>
            </div>
          </div>

          <!-- 正文内容 -->
          <div class="discussion-body">
            <div class="content-text" v-html="renderedContent"></div>
          </div>

          <!-- 互动统计 -->
          <div class="discussion-actions">
            <button 
              :class="['action-btn', { active: discussion.isLiked }]"
              @click="handleLike"
            >
              <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
                <path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-2z"/>
              </svg>
              <span>{{ discussion.likes }}</span>
            </button>
            <button class="action-btn">
              <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
                <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
              </svg>
              <span>{{ discussion.comments }}</span>
            </button>
            <button 
              :class="['action-btn', { active: discussion.isFavorited }]"
              @click="handleFavorite"
            >
              <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
                <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
              </svg>
              <span>{{ discussion.favorites }}</span>
            </button>
            <button class="action-btn">
              <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
                <path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"/>
              </svg>
              分享
            </button>
          </div>

          <!-- 评论区标题 -->
          <div class="comments-header">
            <h2 class="comments-title">
              评论 ({{ comments.length }})
            </h2>
            <div class="sort-buttons">
              <button 
                :class="['sort-btn', { active: sortType === 'hot' }]"
                @click="sortType = 'hot'"
              >
                最热
              </button>
              <button 
                :class="['sort-btn', { active: sortType === 'latest' }]"
                @click="sortType = 'latest'"
              >
                最新
              </button>
            </div>
          </div>

          <!-- 发表评论 -->
          <div class="comment-input-box">
            <div class="input-header">
              <span class="tab active">评论</span>
            </div>
            <div class="input-wrapper">
              <textarea 
                v-model="commentContent"
                class="comment-textarea"
                placeholder="请输入评论... (Ctrl+Enter 发布)"
                rows="4"
                @keydown.ctrl.enter="handleSubmitComment"
              ></textarea>
              <div class="input-footer">
                <div class="toolbar">
                  <button class="tool-btn" title="插入代码">
                    <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
                      <path d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z"/>
                    </svg>
                  </button>
                  <button class="tool-btn" title="插入链接">
                    <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
                      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/>
                    </svg>
                  </button>
                  <button class="tool-btn" title="提及用户">
                    <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
                      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/>
                    </svg>
                  </button>
                </div>
                <button 
                  class="submit-btn"
                  :disabled="!commentContent.trim() || submittingComment"
                  @click="handleSubmitComment"
                >
                  {{ submittingComment ? '发布中...' : '评论' }}
                </button>
              </div>
            </div>
          </div>

          <!-- 评论列表 -->
          <div class="comments-list">
            <div 
              v-for="comment in sortedComments" 
              :key="comment.id"
              class="comment-item"
            >
              <!-- 评论者头像 -->
              <div 
                class="comment-avatar"
                @mouseenter="handleUserHover(comment.author.id, $event)"
                @mouseleave="handleUserLeave"
              >
                <img 
                  v-if="comment.author.avatar" 
                  :src="getAvatarUrl(comment.author.avatar)" 
                  :alt="comment.author.nickname"
                />
                <span v-else class="avatar-text">
                  {{ comment.author.nickname?.charAt(0) || 'U' }}
                </span>
              </div>

              <!-- 评论内容 -->
              <div class="comment-content">
                <div class="comment-header">
                  <span class="commenter-name">{{ comment.author.nickname }}</span>
                  <span v-if="comment.author.badge" class="badge">{{ comment.author.badge }}</span>
                </div>
                <div class="comment-meta">
                  来自 {{ comment.author.location || userInfo?.location || '中国' }} · {{ formatTime(comment.createdAt) }}
                </div>
                <div class="comment-text">{{ comment.content }}</div>
                <div class="comment-actions">
                  <button 
                    :class="['action-btn', { active: comment.isLiked }]"
                    @click="handleLikeComment(comment.id)"
                  >
                    <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                      <path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-2z"/>
                    </svg>
                    <span>{{ comment.likes }}</span>
                  </button>
                  <button 
                    class="action-btn"
                    @click="toggleReplyInput(comment.id)"
                  >
                    <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                      <path d="M10 9V5l-7 7 7 7v-4.1c5 0 8.5 1.6 11 5.1-1-5-4-10-11-11z"/>
                    </svg>
                    回复
                  </button>
                  <button 
                    v-if="comment.replies > 0"
                    class="action-btn"
                    @click="toggleReplies(comment.id)"
                  >
                    <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                      <path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/>
                    </svg>
                    {{ showRepliesMap[comment.id] ? '收起' : '展示' }} {{ comment.replies }} 条回复
                  </button>
                </div>

                <!-- 回复输入框 -->
                <div v-if="replyingCommentId === comment.id" class="reply-input-box">
                  <textarea 
                    v-model="replyContent"
                    class="reply-textarea"
                    :placeholder="`回复 ${comment.author.nickname}... (Ctrl+Enter 发布)`"
                    rows="3"
                    @keydown.ctrl.enter="handleSubmitReply"
                  ></textarea>
                  <div class="reply-actions">
                    <button class="btn-cancel" @click="cancelReply">取消</button>
                    <button 
                      class="btn-submit"
                      :disabled="!replyContent.trim() || submittingReply"
                      @click="handleSubmitReply(comment.id)"
                    >
                      {{ submittingReply ? '发布中...' : '回复' }}
                    </button>
                  </div>
                </div>

                <!-- 回复列表 -->
                <div v-if="showRepliesMap[comment.id] && comment.replyList" class="replies-list">
                  <div 
                    v-for="reply in comment.replyList" 
                    :key="reply.id"
                    class="reply-item"
                  >
                    <div 
                      class="reply-avatar"
                      @mouseenter="handleUserHover(reply.author.id, $event)"
                      @mouseleave="handleUserLeave"
                    >
                      <img 
                        v-if="reply.author.avatar" 
                        :src="getAvatarUrl(reply.author.avatar)" 
                        :alt="reply.author.nickname"
                      />
                      <span v-else class="avatar-text">
                        {{ reply.author.nickname?.charAt(0) || 'U' }}
                      </span>
                    </div>
                    <div class="reply-content">
                      <div class="reply-header">
                        <span class="replier-name">{{ reply.author.nickname }}</span>
                      </div>
                      <div class="reply-text">{{ reply.content }}</div>
                      <div class="reply-meta">
                        {{ formatTime(reply.createdAt) }}
                        <button 
                          :class="['like-btn', { active: reply.isLiked }]"
                          @click="handleLikeComment(reply.id)"
                        >
                          <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
                            <path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-2z"/>
                          </svg>
                          {{ reply.likes }}
                        </button>
                        <button class="reply-btn" @click="toggleReplyInput(comment.id)">回复</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户卡片悬停 -->
    <div 
      v-if="hoveredUser"
      class="user-card-container"
      :style="{
        position: 'absolute',
        top: hoveredUser.position.top + 'px',
        left: hoveredUser.position.left + 'px',
        zIndex: 1000
      }"
      @mouseenter="handleCardHover"
      @mouseleave="handleCardLeave"
    >
      <UserCard 
        :userId="hoverUserId"
        @message="handleMessage"
      />
    </div>

    <!-- 私信列表 -->
    <MessageList
      v-if="showMessageList"
      @close="closeMessageList"
      @openChat="openMessageDialog"
    />

    <!-- 私信对话 -->
    <MessageDialog
      v-if="showMessageDialog"
      :targetUser="messageTargetUser"
      @close="closeMessageDialog"
      @back="backToMessageList"
    />

    <!-- 隐藏的头像上传input -->
    <input 
      type="file" 
      ref="avatarInput" 
      accept="image/*" 
      style="display: none"
      @change="handleAvatarChange"
    />

    <!-- Toast提示 -->
    <Toast ref="toastRef" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { 
  getDiscussionDetail, 
  getComments, 
  createComment, 
  likeDiscussion, 
  favoriteDiscussion,
  likeComment,
  getCommentReplies
} from '../api/discussion'
import { getAvatarUrl } from '../utils/url'
import { uploadAvatar } from '../api/user'
import { renderMathInHTML } from '../utils/renderMath'
import { toast } from '../utils/toast'
import UserCard from '../components/UserCard.vue'
import MessageDialog from '../components/MessageDialog.vue'
import Toast from '../components/Toast.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const userInfo = computed(() => userStore.userInfo)
const showUserMenu = ref(false)

const avatarInput = ref(null)
const toastRef = ref(null)

// 用户卡片悬停
const hoveredUser = ref(null)
const hoverUserId = ref(null)
let hoverTimer = null

// 私信对话
const showMessageList = ref(false)
const showMessageDialog = ref(false)
const messageTargetUser = ref(null)

const discussion = ref(null)
const comments = ref([])
const loading = ref(false)
const sortType = ref('hot')

// 评论相关
const commentContent = ref('')
const submittingComment = ref(false)

// 回复相关
const replyingCommentId = ref(null)
const replyContent = ref('')
const submittingReply = ref(false)
const showRepliesMap = ref({})

const sortedComments = computed(() => {
  const list = [...comments.value]
  if (sortType.value === 'hot') {
    return list.sort((a, b) => b.likes - a.likes)
  } else {
    return list.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
  }
})

// 渲染后的讨论内容（包含数学公式）
const renderedContent = computed(() => {
  if (!discussion.value || !discussion.value.content) return ''
  return renderMathInHTML(discussion.value.content)
})

onMounted(() => {
  // 检查登录状态
  console.log('DiscussionDetail mounted - Token:', userStore.token)
  console.log('DiscussionDetail mounted - UserInfo:', userStore.userInfo)
  
  if (!userStore.token || !userStore.userInfo) {
    console.warn('用户未登录，跳转到登录页')
    router.push('/login')
    return
  }
  
  loadDiscussionDetail()
  loadComments()
})

async function loadDiscussionDetail() {
  loading.value = true
  try {
    const res = await getDiscussionDetail(route.params.id)
    if (res.code === 200) {
      discussion.value = res.data
    }
  } catch (error) {
    console.error('加载讨论详情失败:', error)
    // 模拟数据
    discussion.value = {
      id: route.params.id,
      title: '这一次，我们一起赢回来。🏆',
      content: '<p>大家好，我想和大家讨论一下如何提升数学学习效率的问题。</p><p>最近在学习极限和三角函数，遇到了一些困难，希望能得到大家的帮助和建议。</p><p>有没有好的学习方法和技巧可以分享？</p>',
      author: {
        nickname: 'Kita3',
        avatar: '',
        location: '福建'
      },
      tags: ['极限', '三角函数'],
      likes: 100,
      comments: 27,
      favorites: 121,
      isLiked: false,
      isFavorited: false,
      createdAt: '2025-09-03T10:30:00'
    }
  } finally {
    loading.value = false
  }
}

async function loadComments() {
  try {
    const res = await getComments(route.params.id, {
      page: 1,
      pageSize: 100,
      sort: sortType.value
    })
    if (res.code === 200) {
      comments.value = res.data.list
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    // 模拟数据
    comments.value = [
      {
        id: 1,
        content: '我想夺回冲击力扣的三百六十五块钱😭',
        author: {
          nickname: 'Kita3',
          avatar: '',
          location: '福建',
          badge: null
        },
        likes: 73,
        replies: 8,
        isLiked: false,
        createdAt: '2025-09-03T11:00:00'
      },
      {
        id: 2,
        content: '夺回睡眠',
        author: {
          nickname: 'undercat',
          avatar: '',
          location: '江苏',
          badge: null
        },
        likes: 2,
        replies: 0,
        isLiked: false,
        createdAt: '2025-10-20T14:30:00'
      },
      {
        id: 3,
        content: '懂得成为2000分 🏅',
        author: {
          nickname: 'MathMaster',
          avatar: '',
          location: '江苏',
          badge: '🏅'
        },
        likes: 156,
        replies: 12,
        isLiked: false,
        createdAt: '2025-09-05T16:45:00'
      }
    ]
  }
}

async function handleLike() {
  try {
    const res = await likeDiscussion(discussion.value.id)
    if (res.code === 200) {
      // 使用后端返回的最新数据
      discussion.value.isLiked = res.data.isLiked
      discussion.value.likes = res.data.likes
    }
  } catch (error) {
    console.error('点赞失败:', error)
    toast.error(error.message || '操作失败')
  }
}

async function handleFavorite() {
  try {
    const res = await favoriteDiscussion(discussion.value.id)
    if (res.code === 200) {
      // 使用后端返回的最新数据
      discussion.value.isFavorited = res.data.isFavorited
      discussion.value.favorites = res.data.favorites
    }
  } catch (error) {
    console.error('收藏失败:', error)
    toast.error(error.message || '操作失败')
  }
}

async function handleLikeComment(commentId) {
  try {
    const res = await likeComment(commentId)
    if (res.code === 200) {
      // 使用后端返回的最新数据
      const comment = comments.value.find(c => c.id === commentId)
      if (comment) {
        comment.isLiked = res.data.isLiked
        comment.likes = res.data.likes
      }
    }
  } catch (error) {
    console.error('点赞评论失败:', error)
    toast.error(error.message || '操作失败')
  }
}

async function handleSubmitComment() {
  if (!commentContent.value.trim() || submittingComment.value) return
  
  submittingComment.value = true
  try {
    const res = await createComment(route.params.id, {
      content: commentContent.value
    })
    if (res.code === 200) {
      toast.success('评论成功！')
      commentContent.value = ''
      loadComments()
      if (discussion.value) {
        discussion.value.comments++
      }
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    toast.error(error.message || '发表评论失败，请重试')
  } finally {
    submittingComment.value = false
  }
}

function toggleReplyInput(commentId) {
  if (replyingCommentId.value === commentId) {
    replyingCommentId.value = null
    replyContent.value = ''
  } else {
    replyingCommentId.value = commentId
    replyContent.value = ''
  }
}

function cancelReply() {
  replyingCommentId.value = null
  replyContent.value = ''
}

async function handleSubmitReply(commentId) {
  if (!replyContent.value.trim() || submittingReply.value) return
  
  submittingReply.value = true
  try {
    const res = await createComment(route.params.id, {
      content: replyContent.value,
      parentId: commentId
    })
    if (res.code === 200) {
      toast.success('回复成功！')
      replyContent.value = ''
      replyingCommentId.value = null
      loadComments()
    }
  } catch (error) {
    console.error('回复失败:', error)
    toast.error(error.message || '回复失败，请重试')
  } finally {
    submittingReply.value = false
  }
}

async function toggleReplies(commentId) {
  showRepliesMap.value[commentId] = !showRepliesMap.value[commentId]
  
  // 如果是展开并且还没有加载过回复列表
  if (showRepliesMap.value[commentId]) {
    const comment = comments.value.find(c => c.id === commentId)
    if (comment && !comment.replyList) {
      try {
        const res = await getCommentReplies(commentId, { page: 1, pageSize: 50 })
        if (res.code === 200) {
          comment.replyList = res.data.list
        }
      } catch (error) {
        console.error('加载回复列表失败:', error)
        // 模拟数据
        comment.replyList = [
          {
            id: 101,
            content: '我也想要！',
            author: {
              nickname: 'User1',
              avatar: ''
            },
            likes: 5,
            isLiked: false,
            createdAt: '2025-09-03T11:30:00'
          }
        ]
      }
    }
  }
}

function goBack() {
  router.push('/discussion')
}

// 用户卡片悬停处理
function handleUserHover(userId, event) {
  clearTimeout(hoverTimer)
  hoverTimer = setTimeout(() => {
    hoverUserId.value = userId
    const rect = event.target.closest('.author-avatar, .comment-avatar, .reply-avatar').getBoundingClientRect()
    hoveredUser.value = {
      userId,
      position: {
        top: rect.bottom + window.scrollY + 8,
        left: rect.left + window.scrollX
      }
    }
  }, 300) // 300ms后显示
}

function handleUserLeave() {
  clearTimeout(hoverTimer)
  hoverTimer = setTimeout(() => {
    hoveredUser.value = null
    hoverUserId.value = null
  }, 200)
}

function handleCardHover() {
  clearTimeout(hoverTimer)
}

function handleCardLeave() {
  hoveredUser.value = null
  hoverUserId.value = null
}

// 私信处理
function handleMessage(user) {
  hoveredUser.value = null
  messageTargetUser.value = user
  showMessageDialog.value = true
}

function openMessageList() {
  showMessageList.value = true
}

function closeMessageList() {
  showMessageList.value = false
}

function openMessageDialog(user) {
  showMessageList.value = false
  messageTargetUser.value = user
  showMessageDialog.value = true
}

function closeMessageDialog() {
  showMessageDialog.value = false
  messageTargetUser.value = null
}

function backToMessageList() {
  showMessageDialog.value = false
  showMessageList.value = true
}

function formatTime(dateStr) {
  const date = new Date(dateStr)
  const now = new Date()
  const diff = now - date
  
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN')
}

// 头像上传功能
function handleAvatarClick() {
  avatarInput.value.click()
}

async function handleAvatarChange(event) {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    toastRef.value?.show({
      title: '上传失败',
      message: '请选择图片文件',
      type: 'error'
    })
    return
  }

  // 验证文件大小 (2MB)
  if (file.size > 2 * 1024 * 1024) {
    toastRef.value?.show({
      title: '上传失败',
      message: '图片大小不能超过2MB',
      type: 'error'
    })
    return
  }

  try {
    const formData = new FormData()
    formData.append('avatar', file)

    const { data } = await uploadAvatar(formData)
    
    // 更新用户信息
    userStore.setUserInfo({
      ...userInfo.value,
      avatar: data.avatar
    })

    toastRef.value?.show({
      title: '上传成功',
      message: '头像已更新',
      type: 'success'
    })
  } catch (error) {
    console.error('上传头像失败:', error)
    toastRef.value?.show({
      title: '上传失败',
      message: error.message || '请稍后重试',
      type: 'error'
    })
  } finally {
    // 清空input值，允许重复上传同一文件
    event.target.value = ''
  }
}
</script>

<style lang="scss" scoped>
.discussion-detail-page {
  min-height: 100vh;
  background: #f5f7fa;
}

// 导航栏样式（简化版，复用）
.top-navbar {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 24px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-left {
  .logo-link {
    text-decoration: none;
    display: flex;
    align-items: center;
    gap: 12px;
    
    .logo-icon {
      filter: drop-shadow(0 2px 8px rgba(102, 126, 234, 0.3));
    }
    
    .logo {
      font-size: 24px;
      font-weight: bold;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }
}

.navbar-center {
  display: flex;
  gap: 32px;
  
  .nav-link {
    color: #666;
    text-decoration: none;
    font-size: 15px;
    transition: color 0.2s;
    
    &:hover {
      color: #667eea;
    }
  }
}

.navbar-right {
  display: flex;
  align-items: center;
}

.user-dropdown {
  .user-info-trigger {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 4px 12px 4px 4px;
    border-radius: 24px;
    cursor: pointer;
    
    &:hover {
      background: #f5f5f5;
    }
  }
  
  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-size: 16px;
    font-weight: bold;
    overflow: hidden;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .user-display-name {
    font-size: 14px;
    font-weight: 500;
    color: #333;
  }
}

// 主内容区
.main-content {
  max-width: 900px;
  margin: 0 auto;
  padding: 32px 24px;
}

.content-container {
  background: white;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.back-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: #f5f7fa;
  color: #666;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 24px;
  
  &:hover {
    background: #e8ecf1;
    color: #333;
  }
  
  svg {
    display: block;
  }
}

.loading {
  padding: 80px 0;
  text-align: center;
  color: #999;
  font-size: 16px;
}

.discussion-content {
  .discussion-header {
    padding-bottom: 24px;
    border-bottom: 1px solid #eee;
    margin-bottom: 24px;
  }
  
  .discussion-title {
    font-size: 32px;
    font-weight: bold;
    color: #333;
    margin: 0 0 20px 0;
    line-height: 1.4;
  }
  
  .author-info {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
  }
  
  .author-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    overflow: hidden;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    flex-shrink: 0;
    cursor: pointer;
    transition: transform 0.2s;
    
    &:hover {
      transform: scale(1.05);
    }
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .avatar-text {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 20px;
      font-weight: bold;
    }
  }
  
  .author-details {
    .author-name {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 4px;
    }
    
    .publish-info {
      font-size: 13px;
      color: #999;
    }
  }
  
  .discussion-tags {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    
    .tag {
      padding: 4px 12px;
      background: #f5f7fa;
      color: #667eea;
      border-radius: 4px;
      font-size: 13px;
    }
  }
  
  .discussion-body {
    padding: 24px 0;
    border-bottom: 1px solid #eee;
    margin-bottom: 24px;
    
    .content-text {
      font-size: 16px;
      line-height: 1.8;
      color: #333;
      
      p {
        margin: 0 0 16px 0;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
      
      // 数学公式样式
      :deep(.math-display) {
        display: block;
        margin: 20px 0;
        padding: 16px;
        background: #f9fafb;
        border-radius: 8px;
        overflow-x: auto;
        text-align: center;
        
        .katex-display {
          margin: 0;
        }
      }
      
      :deep(.math-inline) {
        display: inline;
        margin: 0 4px;
        
        .katex {
          font-size: 1.1em;
        }
      }
      
      :deep(.math-error) {
        color: #ff4757;
        background: #fff5f5;
        padding: 2px 8px;
        border-radius: 4px;
        font-family: monospace;
        font-size: 14px;
      }
      
      // 图片样式
      :deep(.content-image),
      :deep(.discussion-image) {
        display: block;
        max-width: 600px;  // 最大宽度600px
        width: 100%;
        height: auto;
        margin: 16px auto;  // 居中显示
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        cursor: pointer;
        transition: transform 0.3s;
        
        &:hover {
          transform: scale(1.02);
          box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
        }
      }
    }
  }
  
  .discussion-actions {
    display: flex;
    gap: 16px;
    padding-bottom: 24px;
    border-bottom: 1px solid #eee;
    margin-bottom: 32px;
    
    .action-btn {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 8px 16px;
      background: #f5f7fa;
      color: #666;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background: #e8ecf1;
        color: #333;
      }
      
      &.active {
        background: #ede7f6;
        color: #667eea;
      }
      
      svg {
        display: block;
      }
    }
  }
  
  .comments-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    
    .comments-title {
      font-size: 20px;
      font-weight: bold;
      color: #333;
      margin: 0;
    }
    
    .sort-buttons {
      display: flex;
      gap: 12px;
      
      .sort-btn {
        padding: 6px 16px;
        background: #f5f7fa;
        color: #666;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.2s;
        
        &:hover {
          background: #e8ecf1;
        }
        
        &.active {
          background: #ede7f6;
          color: #667eea;
        }
      }
    }
  }
  
  .comment-input-box {
    background: #fafbfc;
    border: 1.5px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 24px;
    
    .input-header {
      padding: 12px 16px;
      background: white;
      border-bottom: 1px solid #e0e0e0;
      
      .tab {
        font-size: 14px;
        font-weight: 500;
        color: #667eea;
      }
    }
    
    .input-wrapper {
      background: white;
    }
    
    .comment-textarea {
      width: 100%;
      padding: 16px;
      border: none;
      outline: none;
      font-size: 15px;
      font-family: inherit;
      resize: vertical;
      
      &::placeholder {
        color: #bbb;
      }
    }
    
    .input-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 16px;
      background: #fafbfc;
      
      .toolbar {
        display: flex;
        gap: 8px;
        
        .tool-btn {
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: none;
          border: none;
          border-radius: 4px;
          color: #999;
          cursor: pointer;
          transition: all 0.2s;
          
          &:hover {
            background: #e8ecf1;
            color: #667eea;
          }
          
          svg {
            display: block;
          }
        }
      }
      
      .submit-btn {
        padding: 8px 24px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
        
        &:hover:not(:disabled) {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }
        
        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }
    }
  }
  
  .comments-list {
    .comment-item {
      display: flex;
      gap: 16px;
      padding: 24px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
    }
    
    .comment-avatar {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      overflow: hidden;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      flex-shrink: 0;
      cursor: pointer;
      transition: transform 0.2s;
      
      &:hover {
        transform: scale(1.05);
      }
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .avatar-text {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 20px;
        font-weight: bold;
      }
    }
    
    .comment-content {
      flex: 1;
      min-width: 0;
      
      .comment-header {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 4px;
        
        .commenter-name {
          font-size: 15px;
          font-weight: 600;
          color: #333;
        }
        
        .badge {
          font-size: 14px;
        }
      }
      
      .comment-meta {
        font-size: 13px;
        color: #999;
        margin-bottom: 12px;
      }
      
      .comment-text {
        font-size: 15px;
        line-height: 1.6;
        color: #333;
        margin-bottom: 12px;
      }
      
      .comment-actions {
        display: flex;
        gap: 16px;
        
        .action-btn {
          display: flex;
          align-items: center;
          gap: 4px;
          padding: 4px 8px;
          background: none;
          border: none;
          color: #999;
          font-size: 13px;
          cursor: pointer;
          transition: all 0.2s;
          border-radius: 4px;
          
          &:hover {
            background: #f5f7fa;
            color: #667eea;
          }
          
          &.active {
            color: #667eea;
          }
          
          svg {
            display: block;
          }
        }
      }
    }
  }
  
  .reply-input-box {
    margin-top: 16px;
    padding: 16px;
    background: #fafbfc;
    border-radius: 8px;
    
    .reply-textarea {
      width: 100%;
      padding: 12px;
      border: 1.5px solid #e0e0e0;
      border-radius: 6px;
      font-size: 14px;
      font-family: inherit;
      resize: vertical;
      margin-bottom: 12px;
      
      &:focus {
        outline: none;
        border-color: #667eea;
      }
      
      &::placeholder {
        color: #bbb;
      }
    }
    
    .reply-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      
      button {
        padding: 6px 16px;
        border: none;
        border-radius: 6px;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.2s;
        
        &.btn-cancel {
          background: #f5f7fa;
          color: #666;
          
          &:hover {
            background: #e8ecf1;
          }
        }
        
        &.btn-submit {
          background: #667eea;
          color: white;
          
          &:hover:not(:disabled) {
            background: #5568d3;
          }
          
          &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
          }
        }
      }
    }
  }
  
  .replies-list {
    margin-top: 16px;
    padding-left: 24px;
    border-left: 2px solid #f0f0f0;
    
    .reply-item {
      display: flex;
      gap: 12px;
      padding: 16px 0;
      border-bottom: 1px solid #f5f7fa;
      
      &:last-child {
        border-bottom: none;
      }
    }
    
    .reply-avatar {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      overflow: hidden;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      flex-shrink: 0;
      cursor: pointer;
      transition: transform 0.2s;
      
      &:hover {
        transform: scale(1.05);
      }
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .avatar-text {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 16px;
        font-weight: bold;
      }
    }
    
    .reply-content {
      flex: 1;
      
      .reply-header {
        margin-bottom: 6px;
        
        .replier-name {
          font-size: 14px;
          font-weight: 600;
          color: #333;
        }
      }
      
      .reply-text {
        font-size: 14px;
        line-height: 1.6;
        color: #333;
        margin-bottom: 8px;
      }
      
      .reply-meta {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 12px;
        color: #999;
        
        .like-btn, .reply-btn {
          display: inline-flex;
          align-items: center;
          gap: 3px;
          background: none;
          border: none;
          color: #999;
          font-size: 12px;
          cursor: pointer;
          transition: color 0.2s;
          
          &:hover {
            color: #667eea;
          }
          
          &.active {
            color: #667eea;
          }
          
          svg {
            display: block;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .main-content {
    padding: 16px;
  }
  
  .content-container {
    padding: 20px;
  }
  
  .discussion-title {
    font-size: 24px !important;
  }
}
</style>

